package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.entity.AddressBook;
import com.reggie.service.addressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.reggie.common.R;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Transactional
@RequestMapping("/addressBook")
public class addressBookController {
    @Autowired
    private addressBookService addressBookService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * @param addressBook
     * @return com.reggie.common.R<java.lang.String>
     * @description: 保存用户新建的地址
     * @author 86187
     * @date: 2022/11/24 16:47
     */

    @PostMapping()
    public R<String> addAddress(@RequestBody AddressBook addressBook, HttpSession session) {
        System.out.println(addressBook);
        //给获取的对象创建用户id
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        addressBook.setCreateUser(userId);
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateUser(userId);
        addressBook.setUpdateTime(LocalDateTime.now());
        //保存新建的地址
        boolean save = addressBookService.save(addressBook);
        if (save) {
            //清楚redis中的缓存
            redisTemplate.delete("address:" + session.getAttribute("user"));
            return R.success("新建地址成功!");
        }
        return R.error("新建地址失败!请稍后再试!");
    }

    /**
     * @param session
     * @return com.reggie.common.R<java.util.List < com.reggie.entity.AddressBook>>
     * @description: 查询用户保存的所有地址
     * @author 86187
     * @date: 2022/11/24 17:11
     */

    @GetMapping("/list")
    public R<List<AddressBook>> selectAddressList(HttpSession session) {

        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        //获取用户id
        Long userId = (Long) session.getAttribute("user");
        //判断redis是否存在缓存
        List<AddressBook> addressBooks = (List<AddressBook>) redisTemplate.opsForValue().get("address:" + userId);
        if (addressBooks != null) {
            return R.success(addressBooks);
        }
        //如果redis不存在缓存，则查询数据库
        queryWrapper.eq(userId != null, AddressBook::getUserId, userId);
        List<AddressBook> AddressBookList = addressBookService.list(queryWrapper);
        //将查询好的数据放入redis缓存中
        redisTemplate.opsForValue().set("address:" + userId, AddressBookList);
        return R.success(AddressBookList);
    }

    /**
     * @param addressBook
     * @return com.reggie.common.R<java.lang.String>
     * @description: 将地址修改为默认地址
     * @author 86187
     * @date: 2022/11/24 17:20
     */

    @PutMapping("/default")
    public R<String> defaultAddress(@RequestBody AddressBook addressBook, HttpSession session) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBook.getId() != null, AddressBook::getId, addressBook.getId());
        //将实体类的default修改为默认
        addressBook.setIsDefault(1);
        //秀修改操作进行
        boolean update = addressBookService.update(addressBook, queryWrapper);
        if (update) {
            //清楚redis中的缓存
            redisTemplate.delete("address:" + session.getAttribute("user"));
            return R.success("地址已成功修改为默认地址");
        }
        return R.error("默认地址修改失败!");
    }

    /**
     * @param id
     * @return com.reggie.common.R<com.reggie.entity.AddressBook>
     * @description: 修改地址前返回相应地址的具体的信息
     * @author 86187
     * @date: 2022/11/24 17:23
     */

    @GetMapping("{id}")
    public R<AddressBook> selectUpdateAddressInfo(@PathVariable(value = "id") Long id) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, AddressBook::getId, id);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        return R.success(addressBook);
    }

    /**
     * @param addressBook
     * @return com.reggie.common.R<java.lang.String>
     * @description: 修改地址
     * @author 86187
     * @date: 2022/11/24 17:30
     */

    @PutMapping()
    public R<String> updateAddress(@RequestBody AddressBook addressBook, HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AddressBook> cancelWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBook.getId() != null, AddressBook::getId, addressBook.getId());
        cancelWrapper.eq(userId != null, AddressBook::getUserId, userId);
        //先将其他地址改变为非默认
        //创建对象
        AddressBook cancelDefault = new AddressBook();
        cancelDefault.setIsDefault(0);
        boolean cancel = addressBookService.update(cancelDefault, cancelWrapper);
        //修改地址的修改时间
        addressBook.setUpdateTime(LocalDateTime.now());
        boolean update = addressBookService.update(addressBook, queryWrapper);
        if (update) {
            //清楚redis中缓存,无法保证缓存一定清楚成功，如果失败，则缓存不会进行更新
            redisTemplate.delete("address:" + userId);
            return R.success("修改成功!");
        }
        return R.error("修改失败!");
    }

    /**
     * @param ids
     * @return com.reggie.common.R<java.lang.String>
     * @description: 删除操作
     * @author 86187
     * @date: 2022/11/24 17:35
     */

    @DeleteMapping()
    public R<String> deleteAddress(@RequestParam(value = "ids", required = true) Long[] ids) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, AddressBook::getId, ids);
        List<AddressBook> list = addressBookService.list(queryWrapper);
        //进行删除操作
        boolean remove = addressBookService.remove(queryWrapper);
        if (remove) {
            //清楚redis中地址的缓存
            Set<String> cleanCache = new HashSet<>();
            list.forEach(t -> {
                cleanCache.add("address" + t.getUserId());
            });
            redisTemplate.delete(cleanCache);
            return R.success("删除成功!");
        }
        return R.error("删除失败!系统繁忙或者网络不好!，请稍后再试");
    }

    /**
     * @return com.reggie.common.R<com.reggie.entity.AddressBook>
     * @description: 获取默认地址
     * @author 86187
     * @date: 2022/11/26 10:19
     */

    @GetMapping("/default")
    public R<AddressBook> getDefaultAddress(HttpSession session) {
        AddressBook isDefault = (AddressBook) redisTemplate.opsForValue().get("default");
        if (isDefault != null) {
            return R.success(isDefault);
        }
        Long userId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        queryWrapper.eq(userId != null, AddressBook::getUserId, userId);
        AddressBook defaultAddress = addressBookService.getOne(queryWrapper);
        //缓存
        redisTemplate.opsForValue().set("default", defaultAddress, 60, TimeUnit.MINUTES);
        return R.success(defaultAddress);
    }
}
